<?php

namespace Helper\Controller;

// use Sms\SmsSender;
use Util\StringUtils;
use Common\Controller\ApiController;
use Biz\AliyunSms;

class SmsController extends ApiController {
    /*
     * 发送验证码
     */

    public function sendMobileCode() {
        $input = $this->request();
        $mobile = $input['mobile'];
        $redis = redis();
        \Think\Log::record(json_encode($mobile), '----mobile----',TRUE);
        if($redis->get("mobile_lock_{$mobile}")==1){
             $this->errorResponse(10006);
             \Think\Log::record($redis->get("mobile_lock_{$mobile}"), '----redis缓存----',TRUE);
        }
//        if (S("mobile_lock_{$mobile}") == 1) {
//            $this->errorResponse(10006);
//        }
        $aliyunSms = new AliyunSms();
        try {
            $code = StringUtils::randString(6, 1);
            $result = $aliyunSms->sendMobileCode($mobile, $code);
               \Think\Log::record(json_encode($result), '----mobile----',TRUE);
            if($result){
                $this->setMobileCode($mobile, $code);
                S("mobile_lock_{$mobile}", 1, 60);
            }
            $this->asyncResponse();
        } catch (\Exception $e) {
            $this->errorResponse(70001, $e->getMessage());
        }
    }

    public function sendMobileCode2() {
        $mobile = I('get.mobile');
        if (S("mobile_lock_{$mobile}") == 1) {
            $this->errorResponse(10006);
        }
        $aliyunSms = new AliyunSms();
        try {
            $code = StringUtils::randString(6, 1);
            $aliyunSms->sendMobileCode($mobile, $code);
            $this->setMobileCode($mobile, $code);
            S("mobile_lock_{$mobile}", 1, 60);
            $data = ['code' => 200, 'message' => '发送成功'];
            $this->ajaxReturn($data, 'json');
        } catch (\Exception $e) {
            $data = ['code' => 200, 'message' => '发送失败'];
            $this->ajaxReturn($data, 'json');
//            $this->errorResponse(70001, $e->getMessage());
        }
    }

    public function checkMobileCode2() {
        $input = $this->request();
        $mobile = $input['mobile'];
        $mobileCode = $input['mobile_code'];
        if (!isMobile($mobile)) {
            $this->errorResponse(110029);
        }
        try {
            if (!$this->checkMobileCode($mobile, $mobileCode)) {
                $this->errorResponse(10009);
            }
            $this->asyncResponse();
        } catch (\Exception $e) {
            $this->errorResponse(70001, $e->getMessage());
        }
    }

}
